/*
 * Copyright 2018 Zhongan.com All right reserved. This software is the
 * confidential and proprietary information of Zhongan.com ("Confidential
 * Information"). You shall not disclose such Confidential Information and shall
 * use it only in accordance with the terms of the license agreement you entered
 * into with Zhongan.com.
 */

package com.zhongan.cloud.gateway.filter;

import org.springframework.cloud.gateway.route.RouteLocator;
import org.springframework.cloud.gateway.route.builder.RouteLocatorBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * 路径重写过滤器
 *
 * @author tongyufu
 */
@Configuration
public class RewirtePathFilter {

    @Bean
    public RouteLocator rewritePathRouteLocator(RouteLocatorBuilder builder) {
        return builder.routes().route(r -> r.path("/rewirte/**")
        //固定路径转发
                .filters(f -> f.rewritePath("/rewirte/hello5", "/rewirte/world"))
                //正则表达式动态转发，访问/rewirte/hello5，会被转发到/hello5
                //.filters(f -> f.rewritePath("/rewirte/(?<segment>.*)", "/${segment}"))
                .uri("lb://HELLO-SERVICE")).build();
    }

    /**
     * 302重定向，不影响爬虫和搜索引擎，重定向目标必须是绝对路径
     */
    @Bean
    public RouteLocator rediectPathRouteLocator(RouteLocatorBuilder builder) {
        return builder
                .routes()
                .route(r -> r.path("/redirect/hello").filters(f -> f.redirect(302, "http://www.baidu.com"))
                        .uri("lb://HELLO-SERVICE")).build();
    }
}
